package com.hexiang.client.handler;

import com.hexiang.domain.CommonResponse;
import com.hexiang.exception.ClientException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.ResourceAccessException;

import java.io.Serializable;

public class ClientResponseHandler {

    private static final String CONNECT_TIMED_OUT = "connect timed out";

    private static final String READ_TIMED_OUT = "Read timed out";

    public static <T> CommonResponse<Serializable> handleResponse(String serviceName, ResponseEntity<T> responseEntity) throws ClientException {
        CommonResponse<Serializable> commonResponse;
        // 判断请求是否发生异常
        if (!responseEntity.getStatusCode().is2xxSuccessful()) {
            throw new ClientException(-500, String.format("调用%s服务报错", serviceName));
        } else {
            commonResponse = CommonResponse.builder().body((Serializable) responseEntity.getBody()).succ(true).build();
        }
        return commonResponse;
    }

    public static void handleExceptionThrow(String serviceName, Throwable e) throws ClientException {

        if (e instanceof ResourceAccessException) {
            handleResourceAccessExceptionThrow(serviceName, e);
        } else {
            throw new ClientException(500, String.format("调用服务[%s]报错", serviceName));
        }
    }

    private static void handleResourceAccessExceptionThrow(String serviceName, Throwable e) throws ClientException {
        if (e.getMessage().contains(CONNECT_TIMED_OUT)) {
            throw new ClientException(500, String.format("连接服务[%s]超时", serviceName));
        } else if (e.getMessage().contains(READ_TIMED_OUT)) {
            throw new ClientException(500, String.format("调用服务[%s]超时", serviceName));
        } else {
            throw new ClientException(500, String.format("调用服务[%s]失败", serviceName));
        }
    }
}